import CryptoJS from 'crypto-js';

import {
    server
} from '../server.js'

import {
    setToken
} from './Component/Token.js';

import {
    decryptoAES
} from './Component/Crypto.js';

import {
    mysqlConnectPromise,
    mysqlQueryPromise
} from './Component/MySQLPromise.js';

import {
    respondJson,
    respondSendMessage,
    respondReqDataMalformation,
    respondServerSQLError,
    respondServerQueryError
} from './Component/Respond.js';

export const addAdmin = async (req, res, next) => {

    const body = req.body;

    if (!(body.name && body.password && body.avataruri)) {
        respondReqDataMalformation(res);
        return;
    }

    let pw = decryptoAES(body.password);

    let pool = req.app.locals.pool;

    let connection = await mysqlConnectPromise(pool);

    if (!connection) {
        respondServerSQLError(res);
        return;
    }

    let results = await mysqlQueryPromise(connection, `SELECT max(id) as id_count from admin`);

    if (!results) {
        respondServerQueryError(connection, res);
        return;
    }

    let id_count;
    let avataruri = body.avataruri.split('2333')[1];

    id_count = 10000000 + results[0].id_count + 1;

    let results0 = await mysqlQueryPromise(connection, `INSERT INTO admin(id, name, password, avataruri) values(${id_count}, '${body.name}', '${pw}', '${avataruri}')`);

    if (!results0) {
        respondServerQueryError(connection, res);
        return;
    }

    respondJson(connection, res, 200, {
        status: true,
        info: '注册成功!'
    })

}

export const updateAdmin = async (req, res, next) => {

    const body = req.body;

    if (!(body.id && body.name && body.password && body.uri)) {
        respondReqDataMalformation(res);
        return;
    }

    // undone
    let pw = decryptoAES(body.password);
    let uri = body.uri.split('2333')[1];
    // ----

    let pool = req.app.locals.pool;

    let connection = await mysqlConnectPromise(pool);

    if (!connection) {
        respondServerSQLError(res);
        return;
    }

    let results = await mysqlQueryPromise(connection, `select * from admin where id = ${body.id}`);

    if (!results) {
        respondServerQueryError(connection, res);
        return;
    } else if (results.length == 0) {
        respondJson(connection, res, 200, {
            status: false,
            errinfo: 'no such admin!'
        });
        return;
    }

    var isModified = false;

    if (results[0].name != body.name) {

        await mysqlQueryPromise(connection, `update admin set name = '${body.name}' where id = ${body.id}`);
        isModified = true;

    }
    if (results[0].password != pw) {

        await mysqlQueryPromise(connection, `update admin set password = '${pw}' where id = ${body.id}`);
        isModified = true;

    }
    if (results[0].avataruri != uri) {

        await mysqlQueryPromise(connection, `update admin set avataruri = '${uri}' where id = ${body.id}`);
        isModified = true;

    }

    if (!isModified) {
        respondJson(connection, res, 200, {
            status: true,
            info: 'nothing to change!'
        })
        return;
    }

    respondJson(connection, res, 200, {
        status: true,
        info: 'update success!'
    })
    return;

}

export const removeAdmin = async (req, res, next) => {

    const body = req.body;

    if (!body.id) {
        respondReqDataMalformation(res);
        return;
    }

    let pool = req.app.locals.pool;

    let connection = await mysqlConnectPromise(pool);

    if (!connection) {
        respondServerSQLError(res);
        return;
    }

    let results = await mysqlQueryPromise(connection, `delete from admin where id = ${body.id}`);

    if (!results) {
        respondServerQueryError(connection, res);
        return;
    }

    respondJson(connection, res, 200, {
        status: true,
        info: 'success'
    });
}

export const getAdmin = async (req, res, next) => {

    let pool = req.app.locals.pool;

    let connection = await mysqlConnectPromise(pool);

    if (!connection) {
        respondServerSQLError(res);
        return;
    }

    let results = await mysqlQueryPromise(connection, `select * from admin`);

    if (!results) {
        respondServerQueryError(connection, res);
        return;
    }

    for (let i = 0; i < results.length; i++) {
        results[i].avataruri = server + results[i].avataruri;
    }

    respondSendMessage(connection, res, 200, results);

}

export const adminSignin = async (req, res, next) => {

    const body = req.body

    var username = body.username;
    var password = body.password;

    if (!(username && password)) {
        respondReqDataMalformation(res);
        return;
    }

    let pool = req.app.locals.pool;

    let connection = await mysqlConnectPromise(pool);

    if (!connection) {
        respondServerSQLError(res);
        return;
    }

    let results = await mysqlQueryPromise(connection, `SELECT * from admin where name like '${username}'`);

    if (!results) {
        respondServerQueryError(connection, res);
        return;
    } else if (results.length == 0) {
        respondJson(connection, res, 200, {
            status: 200,
            errinfo: 'admin do not exist'
        })
        return;
    }

    let derivedKey = CryptoJS.PBKDF2(results[0].password, 'iry962g6wd2w39fw', {
        iterations: 100,
        keySize: 32,
        hasher: CryptoJS.algo.SHA512
    });

    let pw = derivedKey.toString();

    if (pw == password) {
        setToken(username, password).then((data) => {
            respondJson(connection, res, 200, {
                status: true,
                avataruri: server + results[0].avataruri,
                token: data
            })
            return;
        })
    } else {
        console.log(pw)
        respondJson(connection, res, 200, {
            status: false,
            errinfo: 'password incorrect!'
        });
        return;
    }

}

export const getUsers = async (req, res, next) => {

    let pool = req.app.locals.pool;

    let connection = await mysqlConnectPromise(pool);

    if (!connection) {
        respondServerSQLError(res);
        return;
    }

    let results = await mysqlQueryPromise(connection, `select userid, username, avataruri, email, isSignOff from users`);

    if (!results) {
        respondServerQueryError(connection, res);
        return;
    }

    for (let i = 0; i < results.length; i++) {
        results[i].avataruri = server + results[i].avataruri;
    }

    respondSendMessage(connection, res, 200, results);

}

export const markFBResolved = async (req, res, next) => {

    const body = req.body;

    let fbid = body.fbid;
    let isResolved = body.isResolved;

    console.log(body)

    let judge = isResolved == true ? true : (isResolved == false ? true : false);

    if (fbid == undefined || isResolved == undefined) {
        respondReqDataMalformation(res);
        return;
    }

    let pool = req.app.locals.pool;

    let connection = await mysqlConnectPromise(pool);

    if (!connection) {
        respondServerSQLError(res);
        return;
    }

    let results = await mysqlQueryPromise(connection, `update feedback set isResolved = ${isResolved} WHERE fbid = ${fbid};`);

    if (!results) {
        respondServerQueryError(connection, res);
        return;
    }

    respondJson(connection, res, 200, {
        status: true,
        info: 'success'
    })

}

export const getDailySearch = async (req, res, next) => {

    let pool = req.app.locals.pool;

    let connection = await mysqlConnectPromise(pool);

    if (!connection) {
        respondServerSQLError(res);
        return;
    }

    // let today = new Date().toLocaleDateString().replaceAll('/', '-');

    let results = await mysqlQueryPromise(connection, `select * from dailySearch where today = CURDATE()`);

    if (!results) {
        respondServerQueryError(connection, res);
        return;
    }

    // console.log(results);

    respondSendMessage(connection, res, 200, results);

}

export const getDailyBrowse = async (req, res, next) => {

    let pool = req.app.locals.pool;

    let connection = await mysqlConnectPromise(pool);

    if (!connection) {
        respondServerSQLError(res);
        return;
    }

    let results = await mysqlQueryPromise(connection, `select * from dailybrowse where today > CURDATE() - 7`);

    if (!results) {
        respondServerQueryError(connection, res);
        return;
    }

    for (let i = 0; i < results.length; i++) {
        let date = new Date(results[i].today)
        let str = date.toLocaleDateString().replaceAll('/', '-');
        results[i].today = str;
    }
    console.log(results);

    respondSendMessage(connection, res, 200, results);

}